'use strict';

module.exports = app => {
    const Sequelize = app.Sequelize;

    const UserModel = app.model.define('user', {
        id: {
            type: Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true,
        },
        username: {
            type: Sequelize.STRING,
        },
        password: {
            type: Sequelize.STRING,
        },
    }, {
            tableName: 'user',
            timestamps: true,
            underscoredAll: true
        });
	/**
	 * 插入数据
	 */
    UserModel.insertUserInfo = (params) => {
        return new Promise((resolve, reject) => {
            UserModel.create({
                username: params.username,
                password: params.password,
            }).then(results => {
                // console.log("UserModel.updateUserInfo-results===", results);
                if (results && results.dataValues) {
                    resolve(results.dataValues);
                } else {
                    reject(false);
                }
            }).catch((err) => {
                console.log('UserModel.updateUserInfo-err===', err);
                reject(err);
            });
        });
    };
	/**
	 * 查询数据
	 * @param {*} params 
	 */
    UserModel.getData = (params) => {
        return new Promise((resolve, reject) => {
            const mixnick = params.mixnick;

            let sql = `SELECT * FROM lamer_user WHERE mixnick='${mixnick}' LIMIT 1`;

            app.model.query(sql).spread((results, metadata) => {

                if (null != results && results.length > 0) {
                    resolve(results[0]);
                } else {
                    resolve({});
                }
            }).catch(err => {
                console.log('UserModel.getData-err======', err);
                reject(err);
            });
        });
    };
	/**
	 * 查询或者新增
	 */
    UserModel.getUserInfo = (params) => {
        return new Promise((resolve, reject) => {
            const mixnick = params.mixnick;
            var creatData = {
                ismember: 0
            };
            UserModel.findOrCreate({
                where: {
                    mixnick: mixnick
                },
                defaults: creatData
            }).then(results => {
                // console.log("UserModel.getUserInfo-results===", results);
                if (results != null) {
                    resolve(results);
                } else {
                    reject(null);
                }
            }).catch((err) => {
                console.log('UserModel.getUserInfo-err===', err);
                reject(err);
            });
        });
    };

    return UserModel;
};